#coding=utf-8
import re,logging, datetime,time
import cgi
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.api.labs import taskqueue

from models import Email

from google.appengine.api import mail

from settings import application

sender = "taobao@%s.appspotmail.com"%application

re_email = re.compile(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)",re.IGNORECASE)

ad ='''
<style type="text/css">
a {text-decoration:none}
</style>

<span style="font-size:20px">
冬天来了，为亲人和自己添件暖暖的冬衣吧 ：-)<br />
店小二向你推荐：<br /><br />
</span>

<span style="font-size:18px;color:#000000;background-color:#ffffff;">For girls:</span>
<br />
1 <a target="_blank" href="http://s.click.taobao.com/a/qXw59YK8YF8=-12837376">月光石女装店</a><br /><br />
<a target="_blank" href="http://s.click.taobao.com/a/qXw59YK8YF8=-12837376"><img style="width:400px;height:208px;" src="http://jpg-server.appspot.com/jpg?name=8317.jpg" alt="" border="0" /></a>
<br />
<br />
2 <a target="_blank" href="http://s.click.taobao.com/a/qXMULjWg1DE=-12837376">快乐购--性价比最高的女装店</a>

<br/>
<br/>
<span style="font-size:18px;color:#000000;background-color:#ffffff;">For Boys</span><br />
1 <a target="_blank" href="http://s.click.taobao.com/a/qXw59YQmuuc=-12837376">型人社 男人装</a><br /><br /><a target="_blank" href="http://s.click.taobao.com/a/qXw59YQmuuc=-12837376"><img src="http://img08.taobaocdn.com/imgextra/i8/24802410/T26AReXhAn7JNXXXXX_%21%2124802410.jpg" title="" alt="" border="0" height="300" width="400" /></a>
<br />
<br />
2 <a target="_blank" href="http://s.click.taobao.com/a/qXMUI0OprT0=-12837376">591mmm.一站式型男购物</a><br /><br /><br /><br /><br />
'''

class EmailImporter(webapp.RequestHandler):
    def get(self):
        addr = self.request.get('e')

        e = Email(addr=addr)        
        e.put()
        #self.response.headers['Content-Type'] = 'text/plain'
        #self.response.out.write(addr)

class MailSender(webapp.RequestHandler):
    def get(self):
        addr = self.request.get('e')
        mail.send_mail(sender=sender,
              to=addr,
              subject="冬天来了，为亲人和自己添件暖暖的冬衣吧 ：-)",
              body='hello', html=ad)
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write(addr)

class MailSender2(webapp.RequestHandler):
    def get(self):
        #self.response.headers['Content-Type'] = 'text/plain'
        q = Email.all()
        q.filter('sent_times =', 0)
        emails = q.fetch(7)
        for e in emails:
            mail.send_mail(sender=sender,
              to=e.addr,
              subject="冬天来了，为亲人和自己添件暖暖的冬衣吧 ：-)",
              body='hello', html=ad)
            e.sent_times = e.sent_times + 1
            e.latest_sent = datetime.date.today()
            e.put()

class MailHandler(InboundMailHandler):
    def receive(self, message):
        _subject = message.subject
        _sender = message.sender
        bodies = message.bodies(content_type='text/plain')
        allBodies = "";
        for body in bodies:
            allBodies = allBodies + "\n---------------------------\n" + body[1].decode()  
        info = '发送者:%s\n标题:%s\n正文:%s\n'%(_sender, _subject, allBodies)
        logging.info(info)

        addrs = []
        emails = re_email.findall(allBodies)
        for e in emails:
            e2 = e.strip()
            if e2.split('@')[-1] in ['taobao-mail1.appspotmail.com', 'google.com']:
                continue
            addrs.append(e2)
        addrs = list(set(addrs))
 
        for addr in addrs:
            query = Email.all()
            query.filter('addr =', addr)
            for e in query.fetch(5):
                e.availabled = False
                e.put()

class Deleter(webapp.RequestHandler):
    def get(self):
        model = self.request.get('model')
        
        q = db.GqlQuery('select * from %s'%model)
        results = q.fetch(101)
        db.delete(results[:100])
        if len(results) == 101:
            taskqueue.add(url='/delete', method='GET', params={'model': model})

from google.appengine.api import urlfetch
class Poster(webapp.RequestHandler):
    def get(self):
      es = Email.all().filter('sent_times =', 1).fetch(10)
      if es:
      
        for e in es:
          url = 'http://forum-email.appspot.com/a?e=%s'%e.addr
          urlfetch.fetch(url)
          
          time.sleep(0.1) 
          
        db.delete(es)
        #taskqueue.add(url='/post2', method='GET')
        
application = webapp.WSGIApplication([
  ('/send_mail', MailSender),
  ('/send_mail2', MailSender2),
  ('/import_mail', EmailImporter),
  ('/delete', Deleter),
  
  ('/post2', Poster),
  MailHandler.mapping(),
], debug=True)

def main():
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
